package com.example.elm.First_Page;

import static android.content.ContentValues.TAG;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.elm.Location_Data;
import com.example.elm.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class First_Page extends AppCompatActivity implements AMapLocationListener {

    BottomNavigationView page_btn;

    Location_Data locationData;
    private ActivityResultLauncher<String> requestPermission;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private class Get_location_Thread extends Thread {
        @Override
        public void run() {
            initLocation();

            while (locationData.getLocation().isEmpty()) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            set_page(new Home_Page(locationData));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_page);

        locationData = new Location_Data();

        requestPermission = registerForActivityResult(new ActivityResultContracts.RequestPermission(), result -> {
            // 权限申请结果
            Log.d(TAG, "权限申请结果: " + result);
        });

        set_page(new Home_Page(locationData));

        if (locationData.getLocation().isEmpty()) {
            Get_location_Thread getLocationThread = new Get_location_Thread();
            getLocationThread.start();
        }

        page_btn = findViewById(R.id.page_btn);
        page_btn.setItemIconTintList(null);
        page_btn.setOnItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int itemId = item.getItemId();

                if (itemId == R.id.home_page) {
                    set_page(new Home_Page(locationData));
                }
                else if (itemId == R.id.vip_page) {
                    set_page(new VIP_Page());
                }
                else if (itemId == R.id.order_page) {
                    set_page(new Order_Page());
                }
                else if (itemId == R.id.setting_page) {
                    set_page(new Setting_Page());
                }

                return true;
            }
        });
    }

    public void set_page(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.set_page, fragment).commit();
    }

    private void initLocation() {
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getApplicationContext());
            //设置定位回调监听
            mLocationClient.setLocationListener(this);
            //初始化AMapLocationClientOption对象
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //获取最近3s内精度最高的一次定位结果
            mLocationOption.setOnceLocationLatest(true);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置定位超时时间，单位是毫秒
            mLocationOption.setHttpTimeOut(20000);
            mLocationOption.setLocationCacheEnable(false);
            mLocationOption.setMockEnable(true);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        if (mLocationClient != null && locationData.getLocation().isEmpty())
            mLocationClient.startLocation();
    }

    /**
     * 停止定位
     */
    private void stopLocation() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 检查是否已经获取到定位权限
        if (checkSelfPermission(First_Page.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // 获取到权限
            Log.d(TAG, "onResume: 已获取到权限");
            startLocation();
        } else {
            // 请求定位权限
            requestPermission.launch(Manifest.permission.ACCESS_FINE_LOCATION);
        }
    }

    private int checkSelfPermission(First_Page firstPage, String accessFineLocation) {
        return 0;
    }

    private void showMsg(CharSequence llw) {
        Toast.makeText(this, llw, Toast.LENGTH_SHORT).show();
    }

    /**
     * 定位回调结果
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null) {
            showMsg("定位失败，aMapLocation 为空");
            return;
        }
        // 获取定位结果
        if (aMapLocation.getErrorCode() == 0) {
            locationData.setLocation(aMapLocation.getAoiName());
            locationData.setCity(aMapLocation.getCity());
            locationData.setLat(aMapLocation.getLatitude());
            locationData.setLng(aMapLocation.getLongitude());
            locationData.setDistrict(aMapLocation.getDistrict());
            locationData.setProvince(aMapLocation.getProvince());
            stopLocation();
        } else {
            // 定位失败
            showMsg("定位失败，错误：" + aMapLocation.getErrorInfo());
            Log.e(TAG,"location Error, ErrCode:"
                    + aMapLocation.getErrorCode() + ", errInfo:"
                    + aMapLocation.getErrorInfo());
        }
    }
}